import { defineStore } from "pinia";
import type { AddressEditInfo } from "vant";
import { AddressInfoType } from "../types/user";
type AddressStateType = {
  addressList: AddressInfoType[];
  editIdx: number; //记录待编辑的地址，新增为-1
  chooseId: string;
};
export const useAddress = defineStore("address", {
  state: (): AddressStateType => ({
    addressList: [
      // {
      //   id: "1",
      //   name: "张三",
      //   tel: "13000000000",
      //   address: "浙江省杭州市西湖区文三路 138 号东方通信大厦 7 楼 501 室",
      //   isDefault: true,
      // },
      // {
      //   id: "2",
      //   name: "李四",
      //   tel: "1310000000",
      //   address: "浙江省杭州市拱墅区莫干山路 50 号",
      // },
    ],
    editIdx: -1,
    chooseId: "",
  }),
  getters: {
    // 根据默认地址、勾选地址，决定订单页显示的地址
    orderAddress(state) {
      // 提取勾选地址
      if (state.chooseId) {
        return state.addressList.find((item) => item.id == state.chooseId);
      }
      return state.addressList.find((item) => item.isDefault);
    },
  },
  actions: {
    // 新增、编辑
    addressAddAction(info: AddressEditInfo) {
      let { province, city, county, addressDetail } = info;
      let obj = {
        ...info,
        address: province + city + county + addressDetail,
        // id:Math.random()+''
      };
      if (info.isDefault) {
        for (let i = 0; i < this.addressList.length; i++) {
          this.addressList[i].isDefault = false;
        }
      }
      //编辑
      if (this.editIdx != -1) {
        console.log("编辑", info);
        let { id } = this.addressList[this.editIdx];
        this.addressList[this.editIdx] = { ...obj, id };
        return;
      }
      //新增
      console.log("新增");
      this.addressList.push({ ...obj, id: Math.random() + "" });
    },
    // 删除
    addressDelAction() {
      this.addressList.splice(this.editIdx, 1);
      this.editIdx = -1;
    },
  },
  persist: {
    key: "pinia-address-2206",
  },
});
